package com.htdata.iiot.file.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wang.wenbo
 * @date 2018/6/15
 */
public class IteratorFileUtil {
    private static Logger logger = LoggerFactory.getLogger(IteratorFileUtil.class);
    private static int level=0;

    public static void IteratorDir(File file,StringBuilder result) throws Exception {
        if(!file.exists()){
            logger.info("该目录《{}》不存在！",file);
            return;
        }
        if(file!=null){
            if(file.isFile()||file.listFiles().length ==0){
                return;
            }else{
                File[] files=file.listFiles();
                files=sort(files);
                for (File f : files) {
                    StringBuilder sb = new StringBuilder();
                    if(f.isFile()){
                        String canonicalPath = f.getCanonicalPath();
                        String substring = canonicalPath.substring(canonicalPath.indexOf(Config.FILE_PATH) + Config.FILE_PATH.length()+1).replaceAll("\\\\", "/");
                        sb.append(Config.SERVER_ADDRESS+substring);
                        sb.append(getTab(level));
                    }
                    result.append(sb.toString());
                    if(f.isDirectory()){
                        level++;
                        IteratorDir(f,result);
                        level--;
                    }
                }
            }
        }
    }

    private static File[] sort(File[] files){
        List<File> flist = new ArrayList<File>();
        for (File f : files) {
            if(f.isDirectory()){
                flist.add(f);
            }
        }
        for (File f : files) {
            if(f.isFile()){
                flist.add(f);
            }

        }
        return flist.toArray(new File[flist.size()]);
    }

    private static String getTab(int level){
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < level; i++) {
            sb.append(",");
        }
        return sb.toString();
    }
}
